//gu:
function ajax(type,url,data,func)
{
  $.ajax({ type: type, url: url, data: data,success: func });
}

function ajax2(type,url,data)
{
  $.ajax({ type: type, url: url, data: data});
}

function save(name,obj){
  localStorage[name] = JSON.stringify(obj)
}
function get(name){
  try{
  return JSON.parse( localStorage[name] )
  }catch(err){ return null;}
}
// application public:
function openContext(name){
  chrome.windows.getCurrent(function(window){
    chrome.tabs.getAllInWindow(window.id,function (tabs){
        // save all tabs to current_context
        oldContext = []
        for(i in tabs){ oldContext.push(tabs[i]) }
        saveContext(getCurrentContextName(),oldContext);
        
        // set the chosen context
        context = getContext(name);
        
        //get open pinned tabs
        pinnedTabs = $(tabs).filter( function(i,tab){return tab.pinned} ).map( function(i,tab){return tab.url} ).toArray()
        //remove pin tabs that are open
        context = $(context).filter( function(i){return $.inArray(context[i].url,pinnedTabs)==-1} ).toArray()
        
        // open context tabs
        for(i in context){ openTab(context[i]); }
        
        // close previous context tabs, except pin tab.
        for(i in tabs){ if(!tabs[i].pinned) {chrome.tabs.remove(tabs[i].id, function(){});} }
    })
  })
}

function saveContextAs(name){
  chrome.windows.getCurrent(function(window){
    chrome.tabs.getAllInWindow(window.id,function (tabs){
        // save all tabs to new name
        context = []
        for(i in tabs){ context.push(tabs[i].url) }
        saveContext(name,context);
    })
  })
}

function deleteContext(name)
{
    if(getCurrentContextName() == name){alert("can't delet current context"); return}
    contexts = get('contexts');
    delete contexts[name];
    save('contexts',contexts);
    location.reload();
}

// application private
function getCurrentContextName()
{
  for(contextName in get('contexts')){ lastContextName = contextName }
  return lastContextName;
}

function openTab(tab){
  tab2 = {}
  for(i in tab)
    if(i=='url' || i=='pinned')
      tab2[i] = tab[i]
  
  chrome.tabs.create(tab2, function(tab){} )
}

function getContext(name){
  contexts = get('contexts')
  context = contexts[name];
  if(context == null){context = [{'url':'http://google.com/search?q='+name}]}
  // re-put in the end. 
  delete contexts[name];
  contexts[name] = context
  save('contexts',contexts)
  
  return context
}

function saveContext(name,context){
  contexts = get('contexts');
  contexts[name] = context
  save('contexts',contexts)
  //update server:
  contextString = JSON.stringify(context)
  ajax2("POST","http://context-switch.appspot.com/context-save","name="+name+"&context="+contextString);
  
  location.reload();
}

